package com.duing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duing.dto.AuthorQueryDTO;
import com.duing.entity.Author;
import com.duing.enums.ErrorCode;
import com.duing.exception.BusinessException;
import com.duing.mapper.AuthorMapper;
import com.duing.service.AuthorService;
import org.springframework.stereotype.Service;



@Service
public class AuthorServiceImpl extends ServiceImpl<AuthorMapper, Author> implements AuthorService {

    public void validateAuthor(Author author){
       if(existsByName(author.getName())){
           throw new BusinessException(ErrorCode.DATA_EXISTS.getCode(), "作者已存在");
       }
    }

    public boolean existsByName(String name){
        QueryWrapper<Author> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public Page<Author> getAuthorsByKeyword(int page, int size, AuthorQueryDTO dto) {

        if(page <= 0 || size <= 0){
            throw new BusinessException(ErrorCode.PARAM_ERROR.getCode(), "分页参数错误");
        }

        Page<Author> authorPage = new Page<>(page, size);
        QueryWrapper<Author> queryWrapper = new QueryWrapper<>();

        if(dto.getName() != null && !dto.getName().isEmpty()){
            queryWrapper.like("name", dto.getName());
        }
        if(dto.getDescription() != null && !dto.getDescription().isEmpty()){
            queryWrapper.like("description", dto.getDescription());
        }

        return (Page<Author>) baseMapper.selectPage(authorPage, queryWrapper);
    }
}
